package records

import (
	"fmt"
	"log"
	"redis_global_key/cache"
	"redis_global_key/config"
	"redis_global_key/handlers/common_cache"
	"redis_global_key/models"
)

//var muClient sync.Mutex

func handleRecordsService() (map[string]interface{}, error) {

	ret := make(map[string]interface{})
	//// TODO 方法一：加锁（实际中接口逻辑比较复杂的话会影响接口的效率）
	//muClient.Lock()
	top100Records, err := getTop100Records()
	//muClient.Unlock()
	if err != nil {
		return nil, err
	}

	ret["records"] = top100Records
	return ret, nil

}

// redis中有记录优先获取redis的数据
func getTop100Records() ([]string, error) {
	// 容易产生一个大key
	redisKey := fmt.Sprintf(cache.Top100WithdrawRecordsKey, config.Conf.App.AppName)

	// TODO 方法二: 保险起见将redis的key设置到分钟级别，这样过了下一分钟旧key过期了，新key产生不会把数据写到旧的key里面
	//currTime := time.Now()
	//currHour := currTime.Hour()
	//currMinute := currTime.Minute()
	//currHourStr := strconv.Itoa(currHour)
	//currMinuteStr := strconv.Itoa(currMinute)
	//currDate := currTime.Format("2006-01-02")
	//redisKey := fmt.Sprintf(cache.Top100WithdrawRecordsKeySafe, config.Conf.App.AppName, currDate, currHourStr, currMinuteStr)

	redisHas, errRedisHas := common_cache.CheckRedisKeyExist(redisKey)
	if errRedisHas != nil {
		return nil, errRedisHas
	}
	// redis有数据就获取redis的
	if redisHas {
		retLst, errLst := common_cache.GetTop100RecordStrInRedis(redisKey)
		if errLst != nil {
			return nil, errLst
		}
		return retLst, nil
	}

	// redis中没有，先从数据库中获取100条数据、构建数据、写入redis中、返回
	recordsLst, errRecordsLst := models.GetTop100UserInfoRecords()
	if errRecordsLst != nil {
		return nil, errRecordsLst
	}
	currRetLst := make([]string, 0)
	for _, recordModel := range recordsLst {
		currUserName := recordModel.UserName
		currAge := recordModel.Age
		currStr := fmt.Sprintf("%s-%d", currUserName, currAge)
		currRetLst = append(currRetLst, currStr)
		errRpush := common_cache.RPushRecordStrToRedis(redisKey, currStr)
		if errRpush != nil {
			// 出错了不影响业务 可以只记录一个log
			log.Println("errRpush: ", errRpush)
			continue
		}
	}
	return currRetLst, nil
}
